#!/usr/bin/env python
# original code by h3k ( michael vandenberghe ) and Inc (Ian Caldwell)
sys.path.append("/usr/share/capsules")
import capsules

db=capsules.capWeb()
db.alias='stable'
db.depalias='stable'
guessDeps=True

cli=capsules.ui()
localCapName=None

def dumperrors():
	if len(capsules.errors) > 0:
		print "\nErrors:"
		for error in capsules.errors:
			print "\t"+error
		print "\n"
		sys.exit(1)

def noGuess(arg):
	global guessDeps
	guessDeps=False
		
def setAlias(alias):
	db.alias=alias
	
def setDepAlias(alias):
	db.depalias=alias
	
def setBothAlias(alias):
	db.alias=alias
	db.depalias=alias

def listCapEntry(keyword):
	"""
		Retrieve an entry from the capsule database, and print it
	"""
	print "\n Retrieving database entry for: '%s'" % keyword
	try:
		entry = db.getEntry(keyword,db.alias)
	except capsules.capsuleDatabaseError, (strerror):
		cli.printError(strerror)
		return
	cli.printCapEntry(entry)
	
def searchDatabase(term):
	"""
		Gets a search from the database, and prints out all the cap entries
	"""
	print "\n Retrieving search for term: '%s'" % term
	try:
		caps = db.getSearch(term,db.alias)
	except capsules.capsuleDatabaseError, (strerror):
		cli.printError(strerror)
		return
	if len(caps) == 0:
		print "\n -- No search results\n"
		return True
	print "|---------------------------------------------------------------------|"
	for cap in caps:
		cli.printCapEntry(cap)
		print "|---------------------------------------------------------------------|"
	print "\n"

def updateDatabase(alias):
	return None

def getCap(keyword):
	"""
		Calls capsules.getcap, ties in event hooks so getcap can report it's progress.
	"""
	versions=capsules.getVersions(keyword)
	if ( len(versions) > 0 ):
		outString = "\t\t"
		for version in versions:
			outString+=keyword+'-'+version+"\n\t\t"
		capsules.errors.append("Package with the keyword '%s' already exists:\n%suse upgrade feature or remove this package first" % (keyword,outString))
		return False
	print "\n Retrieving capsule entry for '"+keyword+"'\n"
	try:
		cap = db.getEntry(keyword,db.alias)
	except capsules.capsuleDatabaseError, (strerror):
		cli.printError(strerror)
		return
	if cap == None:
		print "Cannot find '%s' in the database" % keyword
		return False
	return capsules.getCap(cap,db, cli)

def upgradeLocalCap(capname):
	global localCapName
	localCapName = capname

def upgradeCap(capname):
	"""
		Calls capsules.upgradeCap, ties event hooks so upgrade can report progress
	"""
	cap = capsules.capEntry()
	cap.capname=capname.replace(".cap",'').strip()
	capsules.upgradeCap(cap, db, cli, localCapName, False)

def printDeps(keyword):
	"""
		Prints dep evaluation for capsule specified by keyword
	"""
	print "\n Retrieving capsule entry for '"+keyword+"'\n"
	cap = db.getEntry(keyword,db.alias)
	if cap == None:
		print " -- '%s' not found in database" % keyword
		return False
	
	deps = capsules.resolveDeps(cap)
	if len(deps[0]) > 0:
		print "  Deps Found:"
		for dep in deps[0]:
			print "\t"+dep
	if len(deps[1]) > 0:
		print "  Deps Not Found:"
		for dep in deps[1]:
			print "\t"+dep
	if len(deps[2]) > 0:
		print "  Deps needing upgrade:"
		for dep in deps[2]:
			print "\t"+dep
	print "\n"

def installCap(capname):
	cap = capsules.capEntry()
	cap.capname=capname.replace(".cap",'').strip()
	capsules.installCap(cap,cli)

def removeCap(capname):
	cap = capsules.capEntry()
	cap.capname=capname.replace(".cap",'').strip()
	capsules.removeCap(cap,cli)

def buildCap(capname):
	cap = capsules.capEntry()
	cap.capname=capname.replace(".cap",'').strip()
	capsules.capBuild(cap,cli)

def compressCap(capname):
	cap = capsules.capEntry()
	cap.capname=capname.replace(".cap",'').strip("/").strip()
	capsules.capCompress(cap,cli)

def useGzipCompression(arg):
	capsules.options['compressionType'] = 'gz'

def evaluateDepString(depString):
	print capsules.evaluateDepCheck(depString)
	
def printVersion(keyword):
	ver = capsules.getVersion(keyword)
	if ver == None:
		print "none"
	else:
		print ver
	
def printVersions(keyword):
	vers = capsules.getVersions(keyword)
	if len(vers) > 0:
		print " > Versions installed for '"+keyword+"'"
		for ver in vers:
			print "\t%s" % ver
	else:
		print " - Cannot find any versions for '"+keyword+"'"

def setPath(path):
	"""
		Sets the install path for a capsule
	"""
	print "Setting inpath to '"+path+"'"
	capsules.inpath=path
	capsules.checkCapDir()
	
def setCmd(cmd):
	capsules.trackCommand=cmd

def trackDestdir(arg):
	capsules.capTrackDestDir(cli,guessDeps)
	
def capTrack(capname):
	capsules.capTrack(capname, cli,guessDeps)

def capTrackList(capname):
	capsules.capTrackList(capname, cli)
	
def capTrackListAll(arg):
	capsules.capTrackListAll(cli)

def updateUsingSVN(arg):
	if os.path.exists("/usr/src/capsules"):
		os.chdir("/usr/src/capsules")
		if commands.getoutput("svn --version").split("\n")[0].find("version") > -1:
			print " Retreiving checkout of software"
			status,output = commands.getstatusoutput("svn co svn://arcanelinux.org/arcane/cap-python")
			if status == 0:
				if output.split("\n")[0].find("Checked out revision") > -1:
					print " -- cap-python already the latest"
				else:
					if os.path.exists("cap-python/install.sh"):
						print " > Upgrading cap-python {"
						os.chdir("cap-python")
						if os.system("sh install.sh track") == 0:
							print "}\n ++ upgrade complete"
						else:
							print "}\n -- upgrade failed"
					else:
						print "\n Error: Cannot find cap-python/install.sh\n"
			else:
				print "\n Error: Failed to check out svn://arcanelinux.org/arcane/cap-python\n"
		else:
			print "\n Error: Cannot find svn command in path\n"
	else:
		print "\n Error: Cannot find /usr/src/capsules folder\n"
	sys.exit(0)

def parseArgs():
	"""
		Parse command line arguments
	"""
	options= {
		'--db':setAlias,
		'--dep-db':setDepAlias,
		'-d':setBothAlias,
		'-l':listCapEntry,
		'-s':searchDatabase,
		'--inpath':setPath,
		'-t':capTrack,
		'--pv':printVersions,
		'-p':printVersion,
		'-e':evaluateDepString,
		'-g':getCap,
		'--u_new':upgradeLocalCap,
		'-u':upgradeCap,
		'-b':buildCap,
		'-c':compressCap,
		'--deps':printDeps,
		'-z':useGzipCompression,
		'-i':installCap,
		'-r':removeCap,
		'-h':help,
		'--cmd':setCmd,
		'--no-guess':noGuess,
		'--mb':trackDestdir,
		'--cl':capTrackList,
		'--cL':capTrackListAll,
		"--svn":updateUsingSVN
	}
	try:
		opts, args = getopt.getopt(sys.argv[1:], 
			"d:l:s:g:i:b:c:zhu:r:e:p:t:",
			[
				"db=",
				"dep-db=",
				"deps=",
				"u_new=",
				"inpath=",
				"pv=",
				"cmd=",
				"no-guess",
				"mb",
				"cl=",
				"cL",
				"svn"
			]
		)
	except getopt.GetoptError:
		print "\nError:\n\tInvalid argument\n"
		sys.exit(1)
		
	if len(opts) == 0:
		print "\tBad argument(s)\t\nSee \"-h\" for help...\n"
		
	for opt, arg in opts:
		if options.has_key (opt):
			options [opt](arg)
		else:
			print "Invalid option: " + opt
			sys.exit (1)

def help(arg):
	print """

   Capsules package management system
      Coded by h3k ( Michael Vandenberghe )
   
   Licensed under the GPL, 
      see http://www.gnu.org/copyleft/gpl.html for the full gpl license
   

   >> Database flags

	-l <keyword>
		lists a capsule entry from the capsule database

	-s <term>
		Search for <term> in the capsule database

	-g <keyword>
		Retrieve and install a capsule from the capsule database.
		This also check dependencies, and retrieves those as well

	--deps <keyword>
		Evaluate the dependencies for a capsule entry in the database
		
	-u <captrackname>
		Upgrades capname to latest version
		
	--u_new <capfile>
		Used along with -u to upgrade from <captrackname> to the
		contents of the capsule file specifed by <capfile>

   >> General flags

	-i <capsuleFile>
		Install a capsule from your local path
		
	-r <captrackname>
		Remove a capsule specified by it's captrackname

	--inpath <path>
		Set the working path ( advanced usage )
	
	-d <alias>
		Set both the db alias, and dep db alias to <alias>
		at one time.
	
	--db <alias>
		Set the alias for the capsule database only.
		
	--dep-db <depalias>
		Set a separate alias for resolving dependencies only.

   >> Capsule building flags

	-t <captrackname>
		Track a capsule installation
		
	--cmd <command>
		Set the command to use with -t

	--no-guess
	     Turn off dependency guessing

	-b <captrackname>
		construct a capsule folder for <captrackname>
		
	--mb
	     construct a capsule from the current directory structure in ./
		It will use the current directory name, as the capname, and it will build the filelist.

	-c <captrackFoldername>
		Compress the capsule folder into a capsule.
		By default it uses bz2 compression

	-z
		Alter the compression type for -c to gzip compression.
		Meant to be used with -c

   >> Misc cap functions

	-e <depstring>
		Evaluate a capsule dependency string
	
	--cl <captrackname>
		Print the files from the captrack filelist
		specified by <captrackname>
	
	--cL
		List all the capsules installed on the system

	--pv <keyword>
		Print the versions of the capsules installed
		locally that match <keyword>
		
	--svn
		Updates cap-python using the arcane linux svn repository.
		This will update cap-python to latest development code.

"""

parseArgs()
dumperrors()